import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:gift_listing/common/sqlite/util.dart';

class GiftManager with ChangeNotifier {
  static GiftManager instance = GiftManager();
  final sqliteUtil = SqliteUtil();
  List allGift = [];

  var currentGift;

  void setCurrentGift(gift) {
    currentGift = {
      "id": gift["id"],
      "title": gift["title"],
      "startDate": gift["startDate"],
      "endDate": gift["endDate"],
      "notification": gift["notification"],
      "remark": gift["remark"],
      "gifts": jsonDecode(gift["gifts"])
    };
    notifyListeners();
  }

  void setGiftCompleted(index, value) {
    currentGift['gifts'][index]['completed'] = value ? 1 : 0;
    update(
      id: currentGift['id'],
      title: currentGift['title'],
      startDate: currentGift['startDate'],
      endDate: currentGift['endDate'],
      notification: currentGift['notification'] == 1,
      remark: currentGift['remark'],
      gifts: jsonEncode(currentGift['gifts']),
    );
    notifyListeners();
  }

  void currentGiftRecovery() {
    currentGift = {
      "title": "",
      "startDate": "开始日期",
      "endDate": "结束日期",
      "notification": 1,
      "remark": '',
      "gifts": [
        {
          "gift_name": "",
          "recipient": "",
          "completed": 0,
        }
      ]
    };
    notifyListeners();
  }

  void init() async {
    sqliteUtil.createDb(1);
    refresh();
  }

  Future queryAllGift() async {
    return query("select * from GiftList");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM GiftList");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  void insert({
    int id = 0,
    String title = "",
    String startDate = "",
    String endDate = "",
    bool notification = true,
    String remark = "",
    String gifts = "",
  }) async {
    await sqliteUtil.insert(
        "INSERT INTO GiftList(id,title,startDate,endDate,notification,remark,gifts) VALUES($id,'$title','$startDate','$endDate',$notification,'$remark','$gifts')");
    refresh();
  }

  void update({
    int id = 0,
    String title = "",
    String startDate = "",
    String endDate = "",
    bool notification = true,
    String remark = "",
    String gifts = "",
  }) async {
    await sqliteUtil.update(
      'UPDATE GiftList SET title = ?, startDate = ?, endDate = ?, notification = ?, remark = ?, gifts = ? WHERE id = $id',
      [title, startDate, endDate, notification, remark, gifts],
    );
    refresh();
  }

  void delete({id = ""}) async {
    await sqliteUtil.delete('DELETE FROM GiftList WHERE id = "$id"');
    refresh();
  }

  refresh() {
    queryAllGift().then((res) {
      allGift = res;
      // print(allGift);
      notifyListeners();
    });
  }
}
